package com.qiaofang.service.impl;

import com.qiaofang.common.constant.DelFlagEnum;
import com.qiaofang.dto.ReportDTO;
import com.qiaofang.entity.Customer;
import com.qiaofang.entity.CustomerPremises;
import com.qiaofang.repository.CustomerPremisesRepository;
import com.qiaofang.repository.CustomerRepository;
import com.qiaofang.service.CustomerService;
import com.qiaofang.service.ReportService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CustomerServiceImpl implements CustomerService {

    @Autowired
    private CustomerRepository customerRepository;
    @Autowired
    private CustomerPremisesRepository customerPremisesRepository;
    @Autowired
    private ReportService reportService;


    @Override
    public void addReport2BindCustomer(CustomerPremises customerPremises) {
        Long bindCustomerId = customerPremises.getCustomerId();
        if(Objects.nonNull(bindCustomerId)){
            return;
        }
        boolean createFlag = true;

        Long staffId = customerPremises.getStaffId();
        String mobile = customerPremises.getMobile();
        Customer customer = new Customer();
        customer.setAgentId(staffId);
        customer.setMainMobile(mobile);
        List<Customer> customerList = customerRepository.findAll(Example.of(customer));
        if(CollectionUtils.isNotEmpty(customerList)){

            createFlag = false;
            Customer baseCustomer = customerList.get(0);
            bindCustomerId = baseCustomer.getId();
            if(Objects.isNull(baseCustomer.getOriginalReport())){
                customer = new Customer();
                customer.setId(bindCustomerId);
                customer.setOriginalReport(customerPremises.getId());
                customerRepository.save(customer);
            }
            // 去除重复客户,并变更报备绑定的客户
            filterRepeatCustomer(customerList, baseCustomer);
        }

        // 创建客户
        if(createFlag){
            customer = new Customer();
            customer.setAgentCompany(customerPremises.getStaffCompanyId());
            customer.setAgentId(customerPremises.getStaffId());
            customer.setOriginalReport(customerPremises.getId());
            customer.setRealName(customerPremises.getName());
            customer.setGender(customerPremises.getGender());
            customer.setMainMobile(customerPremises.getMobile());
            customer.setCreateTime(Calendar.getInstance().getTime());
            customer.setDelFlag(DelFlagEnum.UNDEL.getNo());
            customer = customerRepository.save(customer);
            bindCustomerId = customer.getId();
        }
        // 报备绑定客户
        customerPremises.setCustomerId(bindCustomerId);
        customerPremisesRepository.save(customerPremises);
    }

    public void filterRepeatCustomer(List<Customer> customerList, Customer bindCustomer){
        // 不存在或只有唯一的客户时,无需处理
        if(customerList.size() <= 1 || Objects.isNull(bindCustomer)){
            return;
        }
        // 与当前绑定客户不一致的其他客户
        List<Long> repeatCustomerList = customerList.stream()
                // 保证要去除的客户手机号与已绑定的手机号是一致的.
                // 保证都是同一个经纪人.
                // 三种保障,降低客户被错误变更的几率
                .filter(item -> !item.getId().equals(bindCustomer.getId())
                        && item.getMainMobile().equals(bindCustomer.getMainMobile())
                        && item.getAgentId().equals(bindCustomer.getAgentId()))
                .map(item -> item.getId())
                .collect(Collectors.toList());
        // 将重复客户绑定的报备关联客户ID统一改成 bindCustomerId
        if(CollectionUtils.isNotEmpty(repeatCustomerList)){
            ReportDTO reportDTO = new ReportDTO();
            reportDTO.setCustomerId(bindCustomer.getId());
            reportDTO.setCustomerIds(repeatCustomerList);
            reportService.updateCustomerByCustomerIds(reportDTO);
            log.info("change customerids: {} to customerId: {}", repeatCustomerList, bindCustomer.getId());

            // 删除重复客户记录
            List<Customer> updateCustomerList = new ArrayList<>();
            for(Long repeatId: repeatCustomerList){
                Customer customer = new Customer();
                customer.setId(repeatId);
                customer.setDelFlag(DelFlagEnum.DEL.getNo());
                updateCustomerList.add(customer);
            }
            if(CollectionUtils.isNotEmpty(updateCustomerList)){
                customerRepository.saveAll(updateCustomerList);
            }
        }
    }
}
